package com.abc.base.synchronous;

/**
 * ThreadLocal 为每一个线程创建一个单独的副本，参数线程之间独立，互不影响
 *
 *
 */
public class ThreadLocalMain {

   private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
      @Override
      protected Integer initialValue() {
         return 0;
      }
   };

   public int getNextNum() {
      seqNum.set(seqNum.get() + 1);
      return seqNum.get();
   }

   public static void main(String[] args) {
      ThreadLocalMain sn = new ThreadLocalMain();
      ThreadClient t1 = new ThreadClient(sn);
      ThreadClient t2 = new ThreadClient(sn);
      ThreadClient t3 = new ThreadClient(sn);

      t1.start();
      t2.start();
      t3.start();
   }


   private static class ThreadClient extends Thread {
      private ThreadLocalMain sn;

      public ThreadClient(ThreadLocalMain sn) {
         this.sn = sn;
      }

      @Override
      public void run() {
         System.out.println(Thread.currentThread() + " seqNum =" + sn.getNextNum());
      }
   }
}
